#include <stdio.h>
#include <limits.h>

typedef unsigned char *byte_pointer;

// 打印从start地址开始的len个字节
void show_bytes(byte_pointer start, size_t len)
{
    for (size_t i = 0; i < len; ++i)
        printf(" %.2x", start[i]);
    printf("\n");
}
void show_int(int x)
{
    show_bytes((byte_pointer)&x, sizeof(int));
}

/*
    练习题2.15 只用位运算和逻辑运算，实现与x==y等价的C表达式
*/
int eq(int x, int y)
{
    return !(x ^ y);
}

void t0()
{
    int x = 1, y = 1;
    if ((x == y) == eq(x, y))
        printf("Yes\n");
}

void t1()
{
    int x = 4294967295;
    show_int(x);
    show_int(x << 16);
    show_int(x >> 16); // 可以看出，此处的右移是[算术右移]

    printf("*********************\n");
    unsigned int y = 4294967295;
    show_int(y);
    show_int(y >> 16); // 可以看出，此处的右移是[逻辑右移]

    printf("*********************\n");
    int z = 4294967295;
    show_int(z);
    // show_int(z << 33); //error

    printf("*********************\n");
    int a = 0x87;
    show_int(a);
    show_int(a << 3);
}

void t2()
{
    int a = -1;
    show_int(a);
}

void t3()
{
    // short x = 12345;
    // short mx = -x;

    // show_bytes((byte_pointer)&x, sizeof(short));
    // show_bytes((byte_pointer)&mx, sizeof(short));
    short a = -0x58;
    short b = -88;
    // show_bytes((byte_pointer)&a, sizeof(short));
    // show_bytes((byte_pointer)&b, sizeof(short));
    show_bytes((byte_pointer)&a, sizeof(short));
    a = (unsigned short)a;
    show_bytes((byte_pointer)&a, sizeof(short));
}

void t4()
{
    short int v = -12345;
    unsigned short uv = (unsigned short)v;
    printf("v = %d, uv = %u \n", v, uv);

    show_bytes((byte_pointer)&v, sizeof(short));
    show_bytes((byte_pointer)&uv, sizeof(unsigned short));
}

void t5()
{
    unsigned u = UINT_MAX;
    int tu = (int)u;
    printf("u = %u, tu = %d\n", u, tu);
}

void t6()
{
    // unsigned int u = 12345u;
    // int i = 12345;
    // show_int(u);
    // show_int(i);

    unsigned int u = -12345;
    int i = -12345;
    show_int(u);
    show_int(i);
}

void t7()
{
    int x = -1;
    show_int(x);
    printf("-1 ——> %u\n", x);

    long long y = -1;
    show_bytes((byte_pointer)&y, sizeof(long long));
    printf("-1 ——> %llu\n", y);

    printf("INT_MAX: %d\n", INT_MAX);
    printf("UINT_MAX: %u\n", UINT_MAX);
}

void t8()
{
    int x = -1;
    unsigned int y = 4294967295u;
    if(x == y)
        printf("YES\n");
}

int main()
{
    t8();
    return 0;
}